<template>
    <div>
        <div class="table">
            <div class="table-detail">
                <div class="table-detail_left">
                    <img :src="getImage('play.gif')" alt="">
                </div>
                <div class="table-detail_right">
                    <p>当前球桌号: {{ tableDetail.id }}</p>
                    <div v-if="status == 1">
                        <p>使用时长: {{ useTime(tableDetail.status, tableDetail.startTime) }}</p>
                        <p>当前球桌金额: {{ tableDetail.money }}元 / 小时</p>
                        <p>累计使用金额: <span> {{ money }} </span></p>
                        <p>附加商品金额: <span>{{ 11 }}</span></p>
                        <el-button type="danger" class="button-size" @click="playEnd">结束使用</el-button>
                    </div>
                    <div v-if="status == 2" class="detail_right-reservation">
                        <el-button type="success" @click="dialogTableVisible = true">我已到达，立即开始</el-button>
                    </div>
                </div>
            </div>
            <div class="table-shop">
                <ul class="shop-list">
                    <li v-for="item in shop" :key="item.id">
                        <img :src=item.image_url alt="">
                        <p>{{ item.name }}</p>
                        <p>￥ {{ item.price }}</p>
                        <p>剩余{{ item.quantity }}个</p>
                        <el-button @click="addShopMoney('add', item)">添加</el-button>
                        <el-button @click="addShopMoney('sub', item)">删除</el-button>
                    </li>
                </ul>
            </div>
        </div>
        <!-- 预约码对话框 -->
        <el-dialog v-model="dialogTableVisible" title="预约码填写" width="400" style="text-align: center;">
            <el-input style="width: 200px;" v-model="code">预约码</el-input>
            <el-button type="success" @click="tableCheck">提交</el-button>
        </el-dialog>
        <!-- 支付方式对话框 -->
        <el-dialog v-model="payDialog" width="400" :before-close="playStart">
            请选择支付方式:
            <el-button @click="submitMoney(1)">余额支付</el-button>
            <el-button @click="submitMoney(2)">现金支付</el-button>
        </el-dialog>
        <!-- 通过余额支付成功对话框 -->
        <el-dialog v-model="balancePay" width="400">
            <div v-if="balanceStatus == 1">
                <p>余额支付成功，当前余额为 {{ userBalance }}</p>
                <p>即将返回主页面</p>
            </div>
            <div v-else>余额支付失败，当前余额为 {{ userBalance }}</div>
        </el-dialog>
    </div>
</template>

<script setup>
import { getImage } from '@/utils';
import { useRoute, useRouter } from 'vue-router';
import { getTableDetail, computeMoney, check, chooseTable } from '@/api/dashed';
import { pay, payForBanlance } from '@/api/pay'
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { shopList } from '@/api/shop';
import useUserStore from '@/stores/module/user';
const userStore = useUserStore()
const route = useRoute()
const router = useRouter()
const tableDetail = ref({})
const getTable = async () => {
    const { data } = await getTableDetail(route.params.id)
    console.log(data)
    tableDetail.value = data
}
getTable()
//获取球桌状态(预约 or 立即开始)
const status = ref(route.query.status)
//计算使用时长
const useTime = (status, startTime) => {
    const nowdate = Date.now() - startTime
    const hours = Math.floor(nowdate / (1000 * 60 * 60));
    const minutes = Math.floor((nowdate % (1000 * 60 * 60)) / (1000 * 60));
    time.value = nowdate / 1000 / 60
    return `${hours} 小时 ${minutes} 分钟`
}
onMounted(() => {
    watch(status, (newValue) => {
        if (newValue == 1) {
            startTime()
        }
    }, { immediate: true })
})
onUnmounted(() => {
    clearInterval(whileTime)
})
const whileTime = ref(null)
const startTime = () => {
    whileTime.value = setInterval(() => {
        tableDetail.value = { ...tableDetail.value }
    }, 600);
}

//计算球桌时长金额
const time = ref(0)
const money = computed(() => {
    return (time.value * (30 / 60)).toFixed(4)
})

//获取商品列表
const shop = ref('')
const getShopList = async () => {
    const { data } = await shopList()
    shop.value = data.shopList
}
onMounted(() => {
    getShopList()
})
//计算附加商品金额
const shopMoney = ref(0)
const addShopMoney = (func, value) => {
    if (func == 'add') {
        shopMoney.value += value
    }
    if (func == 'sub' && shopMoney.value >= value) {
        shopMoney.value -= value
    }
}

//提交结算
const userBalance = ref('')
const balanceStatus = ref('')
const balancePay = ref(false)
const endTime = ref('')
const playEnd = () => {
    clearInterval(whileTime.value)
    payDialog.value = true
    endTime.value = Date.now()
}

const playStart = () => {
    window.location.reload()
}
const goHome = () => {
    setTimeout(() => {
        router.push('/')
    }, 3000);
}
const iniTable = async () => {
    const res = await chooseTable({ id: route.params.id, status: 0 })
    if (res.message === 'success') {
        goHome()
    }
}

const submitMoney = async (value) => {
    //1.上传提交时的时间戳，计算消费金额
    const { data } = await computeMoney({ id: route.params.id, endTime: endTime.value })
    //2.跳转支付
    if (value == 2) {
        const res = await pay({
            outTradeNo: `${route.params.id}-${userStore.account}-${Math.random() * 10000000}`,
            id: route.params.id,
            endMoney: Number(data),
            userAccount: userStore.account,
            time: endTime.value
        })
        router.push({ name: 'paynow', state: { url: res.url } })
    }
    if (value == 1) {
        const res = await payForBanlance({
            outTradeNo: `${route.params.id}-${userStore.account}-${Math.random() * 10000000}`,
            id: route.params.id,
            endMoney: Number(data),
            userAccount: userStore.account,
            time: endTime.value
        })
        const { data: balanceData } = res
        userBalance.value = balanceData.balance
        balanceStatus.value = balanceData.payStatus
        balancePay.value = true
        if (balanceStatus.value == 1) {
            iniTable()
        }
    }
}

//预约管理
const dialogTableVisible = ref(false)
const code = ref(null)
//预约校验
const tableCheck = async () => {
    const { data } = await check({ id: route.params.id, reqCode: code })
    if (data.allow === 1) {
        dialogTableVisible.value = false
        code.value = null
        ElMessage({
            type: 'success',
            message: "校验成功，开始计时"
        })
        status.value = 1
        getTable()
    }
}
//选择支付方式
const payDialog = ref(false)
</script>

<style lang="scss" scoped>
.table {
    box-sizing: border-box;
    padding: 20px 0;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .table-detail {
        margin: 0 auto;
        max-width: 1200px;

        p {
            font-size: 28px;
        }

        .table-detail_right {
            p {
                margin: 10px 0;
            }

            .button-size {
                width: 400px;
                height: 50px;
                font-size: 16px;
            }

            span {
                color: red;
            }

            .detail_right-reservation {
                text-align: center;

            }
        }
    }

    .table-shop {
        .shop-list {
            display: flex;
            flex-wrap: wrap;
            justify-content: space-around;

            img {
                height: 140px;
                width: 140px;
            }

            p {
                text-align: center;
                font-size: 16px;
            }
        }
    }
}

/* Media Queries for Mobile Devices */
@media screen and (max-width: 768px) {
    .table {
        .table-detail {
            flex-direction: column;
            align-items: center;
            text-align: center;

            .table-detail_left,
            .table-detail_right {
                width: 100%;

                .button-size {
                    width: 100%;
                    height: 40px;
                    font-size: 16px;
                }

                img {
                    height: 100px;
                    width: 200px;
                }

                p {
                    font-size: 16px;
                }
            }


        }

        .table-shop {
            padding-top: 30px;
            text-align: center;

            .shop-list {
                flex-direction: column;
                align-items: center;

                li {
                    margin-bottom: 20px;
                }

                img {
                    height: 100px;
                    width: 100px;
                }

                p {
                    font-size: 14px;
                }
            }
        }
    }
}

@media screen and (max-width: 480px) {
    .table {
        .table-detail {
            p {
                font-size: 16px;
            }
        }

        .table-shop .shop-list {
            img {
                height: 100px;
                width: 100px;
            }

            p {
                font-size: 12px;
            }
        }
    }
}
</style>
